#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
操作录制器模块
负责录制鼠标和键盘操作
"""

import time
import threading
from pynput import mouse, keyboard
from pynput.mouse import Button
from pynput.keyboard import Key


class OperationRecorder:
    """操作录制器类"""
    
    def __init__(self):
        self.operations = []
        self.is_recording = False
        self.start_time = None
        
        # 监听器
        self.mouse_listener = None
        self.keyboard_listener = None
        
        # 用于防止重复记录的变量
        self.last_mouse_time = 0
        self.last_key_time = 0
        self.mouse_threshold = 0.01  # 鼠标移动记录间隔（秒）
        self.key_threshold = 0.01    # 按键记录间隔（秒）
    
    def start_recording(self):
        """开始录制操作"""
        if self.is_recording:
            return
        
        self.is_recording = True
        self.operations.clear()
        self.start_time = time.time()
        
        print("开始录制操作...")
        
        # 创建鼠标监听器
        self.mouse_listener = mouse.Listener(
            on_move=self.on_mouse_move,
            on_click=self.on_mouse_click,
            on_scroll=self.on_mouse_scroll
        )
        
        # 创建键盘监听器
        self.keyboard_listener = keyboard.Listener(
            on_press=self.on_key_press,
            on_release=self.on_key_release
        )
        
        # 启动监听器
        self.mouse_listener.start()
        self.keyboard_listener.start()
        
        # 等待监听器结束
        self.mouse_listener.join()
        self.keyboard_listener.join()
    
    def stop_recording(self):
        """停止录制操作"""
        if not self.is_recording:
            return
        
        self.is_recording = False
        
        # 停止监听器
        if self.mouse_listener:
            self.mouse_listener.stop()
        if self.keyboard_listener:
            self.keyboard_listener.stop()
        
        print(f"录制完成，共记录 {len(self.operations)} 个操作")
    
    def get_relative_time(self):
        """获取相对于开始时间的时间戳"""
        return time.time() - self.start_time
    
    def on_mouse_move(self, x, y):
        """鼠标移动事件"""
        if not self.is_recording:
            return
        
        current_time = time.time()
        if current_time - self.last_mouse_time < self.mouse_threshold:
            return
        
        self.last_mouse_time = current_time
        
        operation = {
            'type': 'mouse_move',
            'x': x,
            'y': y,
            'timestamp': self.get_relative_time()
        }
        self.operations.append(operation)
    
    def on_mouse_click(self, x, y, button, pressed):
        """鼠标点击事件"""
        if not self.is_recording:
            return
        
        # 转换按钮类型为字符串
        button_name = self.button_to_string(button)
        
        operation = {
            'type': 'mouse_click',
            'x': x,
            'y': y,
            'button': button_name,
            'pressed': pressed,
            'timestamp': self.get_relative_time()
        }
        self.operations.append(operation)
    
    def on_mouse_scroll(self, x, y, dx, dy):
        """鼠标滚轮事件"""
        if not self.is_recording:
            return
        
        operation = {
            'type': 'mouse_scroll',
            'x': x,
            'y': y,
            'dx': dx,
            'dy': dy,
            'timestamp': self.get_relative_time()
        }
        self.operations.append(operation)
    
    def on_key_press(self, key):
        """按键按下事件"""
        if not self.is_recording:
            return
        
        current_time = time.time()
        if current_time - self.last_key_time < self.key_threshold:
            return
        
        self.last_key_time = current_time
        
        # 转换按键为字符串
        key_name = self.key_to_string(key)
        
        operation = {
            'type': 'key_press',
            'key': key_name,
            'timestamp': self.get_relative_time()
        }
        self.operations.append(operation)
    
    def on_key_release(self, key):
        """按键释放事件"""
        if not self.is_recording:
            return
        
        # 转换按键为字符串
        key_name = self.key_to_string(key)
        
        operation = {
            'type': 'key_release',
            'key': key_name,
            'timestamp': self.get_relative_time()
        }
        self.operations.append(operation)
        
        # 检查是否按下了停止录制的快捷键 (Esc)
        if key == Key.esc:
            print("检测到ESC键，停止录制")
            threading.Thread(target=self.stop_recording).start()
    
    def button_to_string(self, button):
        """将鼠标按钮转换为字符串"""
        if button == Button.left:
            return 'left'
        elif button == Button.right:
            return 'right'
        elif button == Button.middle:
            return 'middle'
        else:
            return str(button)
    
    def key_to_string(self, key):
        """将按键转换为字符串"""
        try:
            # 尝试获取字符
            if hasattr(key, 'char') and key.char is not None:
                return key.char
            else:
                # 特殊按键
                return key.name if hasattr(key, 'name') else str(key)
        except AttributeError:
            return str(key)
    
    def get_operations_summary(self):
        """获取操作摘要"""
        if not self.operations:
            return "无操作记录"
        
        mouse_moves = sum(1 for op in self.operations if op['type'] == 'mouse_move')
        mouse_clicks = sum(1 for op in self.operations if op['type'] == 'mouse_click' and op['pressed'])
        key_presses = sum(1 for op in self.operations if op['type'] == 'key_press')
        scrolls = sum(1 for op in self.operations if op['type'] == 'mouse_scroll')
        
        total_time = self.operations[-1]['timestamp'] if self.operations else 0
        
        return f"""操作摘要:
总时长: {total_time:.2f}秒
鼠标移动: {mouse_moves}次
鼠标点击: {mouse_clicks}次
按键操作: {key_presses}次
滚轮操作: {scrolls}次
总操作数: {len(self.operations)}个"""
    
    def clear_operations(self):
        """清空操作记录"""
        self.operations.clear()
        print("操作记录已清空")
    
    def save_operations_to_file(self, filename):
        """保存操作到文件"""
        import json
        
        data = {
            'operations': self.operations,
            'total_time': self.operations[-1]['timestamp'] if self.operations else 0,
            'operation_count': len(self.operations)
        }
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            print(f"操作已保存到: {filename}")
            return True
        except Exception as e:
            print(f"保存失败: {e}")
            return False
    
    def load_operations_from_file(self, filename):
        """从文件加载操作"""
        import json
        
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            self.operations = data.get('operations', [])
            print(f"从 {filename} 加载了 {len(self.operations)} 个操作")
            return True
        except Exception as e:
            print(f"加载失败: {e}")
            return False